<%-- web/admin/user-management.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.bookmanager.model.User" %>
<%@ page import="java.util.List" %>
<%
    // 检查管理员权限
    User currentUser = (User) session.getAttribute("user");
    if (currentUser == null || !"admin".equals(currentUser.getRole())) {
        response.sendRedirect("../login.jsp");
        return;
    }

    List<User> users = (List<User>) request.getAttribute("users");
    String searchKeyword = (String) request.getAttribute("searchKeyword");
%>
<html>
<head>
    <title>用户管理 - 图书管理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: #f5f7fa;
            color: #333;
        }

        .header {
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            padding: 0 20px;
        }

        .nav-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1200px;
            margin: 0 auto;
            height: 70px;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
        }

        .admin-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .admin-badge {
            background: #28a745;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .logout-btn {
            padding: 8px 16px;
            background: #dc3545;
            color: white;
            text-decoration: none;
            border-radius: 5px;
            font-size: 0.9rem;
        }

        .container {
            max-width: 1400px;
            margin: 30px auto;
            padding: 0 20px;
        }

        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
        }

        .page-title {
            font-size: 1.8rem;
            color: #333;
        }

        .user-table {
            width: 100%;
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .user-table th,
        .user-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #f0f0f0;
        }

        .user-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #555;
            border-bottom: 2px solid #e9ecef;
        }

        .user-table tr:hover {
            background: #f8f9fa;
        }

        .role-admin {
            background: #28a745;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .role-reader {
            background: #667eea;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .btn {
            padding: 6px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.8rem;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }

        .btn-primary {
            background: #007bff;
            color: white;
        }

        .btn-warning {
            background: #ffc107;
            color: #212529;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
            background: white;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .empty-icon {
            font-size: 4rem;
            margin-bottom: 20px;
            opacity: 0.5;
        }

        .stats-cards {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .stat-icon {
            font-size: 2rem;
            margin-bottom: 10px;
        }

        .stat-number {
            font-size: 1.8rem;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }

        .search-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            margin-bottom: 25px;
        }

        .search-form {
            display: flex;
            gap: 10px;
            max-width: 500px;
        }

        .search-input {
            flex: 1;
            padding: 10px 15px;
            border: 2px solid #e9ecef;
            border-radius: 6px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .search-input:focus {
            outline: none;
            border-color: #667eea;
        }

        .search-btn {
            padding: 10px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 1rem;
            transition: background 0.3s ease;
        }

        .search-btn:hover {
            background: #5a6fd8;
        }

        .clear-search {
            padding: 10px 15px;
            background: #6c757d;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-size: 1rem;
            transition: background 0.3s ease;
        }

        .clear-search:hover {
            background: #5a6268;
        }

        .search-results-info {
            margin-top: 15px;
            color: #666;
            font-size: 0.9rem;
        }

        .search-highlight {
            background: #fff3cd;
            padding: 2px 4px;
            border-radius: 3px;
            font-weight: 500;
        }
    </style>
</head>
<body>
<!-- 顶部导航 -->
<div class="header">
    <div class="nav-bar">
        <div class="logo">📚 图书管理系统</div>
        <div class="admin-info">
            <span>欢迎，<strong><%= currentUser.getUsername() %></strong></span>
            <span class="admin-badge">管理员</span>
            <a href="<%= request.getContextPath() %>/logout" class="logout-btn">退出登录</a>
        </div>
    </div>
</div>

<div class="container">
    <!-- 页面头部 -->
    <div class="page-header">
        <h1 class="page-title">👥 用户管理</h1>
        <div>
            <a href="../admin/dashboard.jsp" class="btn btn-secondary">返回控制台</a>
            <a href="user-add.jsp" class="btn btn-primary">添加用户</a>
        </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
        <form class="search-form" action="user-management" method="get">
            <input type="hidden" name="action" value="search">
            <input type="text"
                   name="keyword"
                   class="search-input"
                   placeholder="输入用户ID、用户名或邮箱进行搜索..."
                   value="<%= searchKeyword != null ? searchKeyword : "" %>">
            <button type="submit" class="search-btn">🔍 搜索</button>
            <% if (searchKeyword != null && !searchKeyword.isEmpty()) { %>
            <a href="user-management" class="clear-search">清除搜索</a>
            <% } %>
        </form>

        <% if (searchKeyword != null && !searchKeyword.isEmpty()) { %>
        <div class="search-results-info">
            搜索 "<span class="search-highlight"><%= searchKeyword %></span>" 的结果，共找到 <strong><%= users != null ? users.size() : 0 %></strong> 个用户
        </div>
        <% } %>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
        <div class="stat-card">
            <div class="stat-icon">👥</div>
            <div class="stat-number" id="totalUsers">0</div>
            <div class="stat-label">总用户数</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">👑</div>
            <div class="stat-number" id="adminUsers">0</div>
            <div class="stat-label">管理员</div>
        </div>
        <div class="stat-card">
            <div class="stat-icon">📖</div>
            <div class="stat-number" id="readerUsers">0</div>
            <div class="stat-label">普通用户</div>
        </div>
    </div>

    <!-- 用户表格 -->
    <% if (users != null && !users.isEmpty()) { %>
    <div style="overflow-x: auto;">
        <table class="user-table">
            <thead>
            <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>手机号</th>
                <th>角色</th>
                <th>注册时间</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <% for (User user : users) { %>
            <tr>
                <td><%= user.getUserId() %></td>
                <td><strong><%= user.getUsername() %></strong></td>
                <td><%= user.getEmail() != null ? user.getEmail() : "未设置" %></td>
                <td><%= user.getPhone() != null ? user.getPhone() : "未设置" %></td>
                <td>
                    <span class="role-<%= user.getRole() %>">
                        <%= "admin".equals(user.getRole()) ? "管理员" : "普通用户" %>
                    </span>
                </td>
                <td><%= user.getCreateTime() != null ? user.getCreateTime().toLocalDate().toString() : "未知" %></td>
                <td>
                    <div class="action-buttons">
                        <button class="btn btn-primary" onclick="editUser('<%= user.getUserId() %>')">编辑</button>
                        <button class="btn btn-warning" onclick="resetPassword('<%= user.getUserId() %>')">重置密码</button>
                        <% if (!user.getUserId().equals(currentUser.getUserId())) { %>
                        <button class="btn btn-danger" onclick="deleteUser('<%= user.getUserId() %>', '<%= user.getUsername() %>')">删除</button>
                        <% } %>
                    </div>
                </td>
            </tr>
            <% } %>
            </tbody>
        </table>
    </div>
    <% } else { %>
    <div class="empty-state">
        <div class="empty-icon">
            <% if (searchKeyword != null && !searchKeyword.isEmpty()) { %>
            🔍
            <% } else { %>
            👥
            <% } %>
        </div>
        <h3>
            <% if (searchKeyword != null && !searchKeyword.isEmpty()) { %>
            未找到相关用户
            <% } else { %>
            暂无用户数据
            <% } %>
        </h3>
        <p>
            <% if (searchKeyword != null && !searchKeyword.isEmpty()) { %>
            没有找到与 "<span style="color: #667eea; font-weight: 500;"><%= searchKeyword %></span>" 相关的用户
            <% } else { %>
            系统中还没有注册用户
            <% } %>
        </p>
        <% if (searchKeyword != null && !searchKeyword.isEmpty()) { %>
        <a href="user-management" class="btn btn-secondary" style="margin-top: 15px;">查看所有用户</a>
        <% } else { %>
        <a href="user-add.jsp" class="btn btn-primary" style="margin-top: 15px;">添加第一个用户</a>
        <% } %>
    </div>
    <% } %>
</div>

<script>
    // 统计信息计算
    function calculateStats() {
        const users = <%= users != null ? users.size() : 0 %>;
        const admins = <%= users != null ? users.stream().filter(u -> "admin".equals(u.getRole())).count() : 0 %>;
        const readers = <%= users != null ? users.stream().filter(u -> "reader".equals(u.getRole())).count() : 0 %>;

        document.getElementById('totalUsers').textContent = users;
        document.getElementById('adminUsers').textContent = admins;
        document.getElementById('readerUsers').textContent = readers;
    }

    // 操作函数
    function editUser(userId) {
        window.location.href = 'edit-user?userId=' + userId;
    }

    function resetPassword(userId, username) {
        window.location.href = 'reset-password.jsp?userId=' + userId + '&username=' + encodeURIComponent(username);
    }

    // 删除用户函数
    function deleteUser(userId, username) {
        console.log('删除用户:', userId, username);
        if (confirm('确定要删除用户 "' + username + '" 吗？此操作不可恢复！')) {
            showDeleteConfirm(userId, username);
        }
    }

    // 显示删除确认对话框 - 修复模板字符串问题
    function showDeleteConfirm(userId, username) {
        console.log('显示确认对话框:', userId, username);

        // 转义特殊字符，防止模板字符串解析错误
        const safeUsername = username.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        const safeUserId = userId.replace(/"/g, '&quot;').replace(/'/g, '&#39;');

        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        `;

        modal.innerHTML = `
            <div style="background: white; padding: 30px; border-radius: 10px; max-width: 500px; width: 90%;">
                <h3 style="margin-bottom: 15px; color: #dc3545;">⚠️ 确认删除用户</h3>
                <p style="margin-bottom: 20px; line-height: 1.5;">
                    您即将删除用户 <strong>"${safeUsername}"</strong> (ID: ${safeUserId})<br>
                    <span style="color: #666; font-size: 0.9rem;">此操作不可恢复，请谨慎操作！</span>
                </p>
                <div style="display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="button" onclick="closeModal()"
                            style="padding: 8px 16px; border: 1px solid #6c757d; background: white; color: #6c757d; border-radius: 4px; cursor: pointer;">
                        取消
                    </button>
                    <button type="button" id="deleteConfirmBtn"
                            style="padding: 8px 16px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        删除用户
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 为删除按钮添加事件监听器，避免模板字符串问题
        document.getElementById('deleteConfirmBtn').addEventListener('click', function() {
            performDelete(userId, username, false, this);
        });

        // 添加关闭模态框的函数
        window.closeModal = function() {
            if (modal && modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
        };
    }

    // 执行删除操作 - 修复事件对象问题
    function performDelete(userId, username, forceDelete, button) {
        console.log('执行删除:', userId, username, forceDelete);

        // 显示加载状态
        if (button) {
            const originalText = button.innerHTML;
            button.innerHTML = '删除中...';
            button.disabled = true;
        }

        // 使用 URLSearchParams 而不是 FormData
        const params = new URLSearchParams();
        params.append('action', 'delete');
        params.append('userId', userId);
        if (forceDelete) {
            params.append('forceDelete', 'true');
        }

        // 发送AJAX请求
        fetch('user-management', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString()
        })
            .then(response => {
                console.log('响应状态:', response.status);
                if (!response.ok) {
                    throw new Error('网络响应不正常: ' + response.status);
                }
                return response.json();
            })
            .then(data => {
                console.log('响应数据:', data);
                if (data.success) {
                    showSuccessMessage(data.message || '用户删除成功');
                    // 2秒后刷新页面
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                } else {
                    // 如果是关联数据错误，显示强制删除选项
                    if (data.message && (data.message.includes('未归还的图书') || data.message.includes('收藏记录'))) {
                        showForceDeleteOption(userId, username, data.message);
                    } else {
                        showErrorMessage(data.message || '删除失败');
                    }
                }
            })
            .catch(error => {
                console.error('删除失败:', error);
                showErrorMessage('删除失败: ' + error.message);
                // 恢复按钮状态
                if (button) {
                    button.innerHTML = '删除用户';
                    button.disabled = false;
                }
            });
    }

    // 显示强制删除选项
    function showForceDeleteOption(userId, username, errorMessage) {
        // 先关闭现有的模态框
        closeModal();

        // 转义特殊字符
        const safeUsername = username.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        const safeUserId = userId.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
        const safeErrorMessage = errorMessage.replace(/"/g, '&quot;').replace(/'/g, '&#39;');

        const modal = document.createElement('div');
        modal.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        `;

        modal.innerHTML = `
            <div style="background: white; padding: 30px; border-radius: 10px; max-width: 500px; width: 90%;">
                <h3 style="margin-bottom: 15px; color: #ffc107;">⚠️ 无法直接删除</h3>
                <p style="margin-bottom: 15px; line-height: 1.5; color: #666;">
                    ${safeErrorMessage}
                </p>
                <p style="margin-bottom: 20px; line-height: 1.5; font-size: 0.9rem; color: #dc3545;">
                    <strong>警告：</strong>强制删除会同时删除该用户的所有关联数据（借阅记录、收藏记录等）！
                </p>
                <div style="display: flex; gap: 10px; justify-content: flex-end;">
                    <button type="button" onclick="closeModal()"
                            style="padding: 8px 16px; border: 1px solid #6c757d; background: white; color: #6c757d; border-radius: 4px; cursor: pointer;">
                        取消
                    </button>
                    <button type="button" id="forceDeleteBtn"
                            style="padding: 8px 16px; background: #dc3545; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        强制删除
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 为强制删除按钮添加事件监听器
        document.getElementById('forceDeleteBtn').addEventListener('click', function() {
            performDelete(userId, username, true, this);
        });
    }

    // 显示成功消息
    function showSuccessMessage(message) {
        showMessage(message, 'success');
    }

    // 显示错误消息
    function showErrorMessage(message) {
        showMessage(message, 'error');
    }

    // 显示消息
    function showMessage(message, type) {
        const messageDiv = document.createElement('div');
        const backgroundColor = type === 'success' ? '#28a745' : '#dc3545';

        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${backgroundColor};
            color: white;
            padding: 15px 20px;
            border-radius: 5px;
            z-index: 1001;
            max-width: 400px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        `;

        messageDiv.innerHTML = `
            <div style="display: flex; align-items: center; gap: 10px;">
                <span>${type == 'success' ? '✅' : '❌'}</span>
                <span>${message}</span>
            </div>
        `;

        document.body.appendChild(messageDiv);

        // 3秒后自动消失
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 3000);
    }

    // 页面加载完成后计算统计信息
    document.addEventListener('DOMContentLoaded', calculateStats);

    // 搜索框回车提交
    document.querySelector('.search-input')?.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            this.form.submit();
        }
    });
</script>
</body>
</html>
